package com.iwinding.ladygg.ui.act;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.EMConstant;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.callback.ContactsCallback;
import com.iwinding.ladygg.net.request.SetNoticesReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.UserRp;
import com.iwinding.ladygg.ui.adapter.PromptContactAdapter;
import com.iwinding.ladygg.ui.view.PromptContactList;
import com.iwinding.ladygg.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by hezhiyong on 2017/4/20.
 */

public class PromptActivity extends BaseActivity implements AdapterView.OnItemClickListener, PromptContactAdapter.OnUserEvent {

    protected ImageButton clearSearch;
    protected EditText query;
    protected ListView listView;
    protected PromptContactList contactListLayout;

    protected InputMethodManager inputMethodManager;

    protected List<EaseUser> contactList;
    protected List<UserRp> contactUsers;
    protected List<UserRp> notices;
    private Map<String, EaseUser> contactsMap;

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_prompt;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        initView();
        setLinster();
        updateNotices();
        refresh();
    }

    void initView() {
        setRightTxtResId(R.string.icane_save);
        setTitleResId(R.string.icane_contacts);


        contactListLayout = (PromptContactList) findViewById(R.id.contact_list);
        listView = contactListLayout.getListView();
        query = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        setUpView();
    }

    void setUpView() {
        notices = new ArrayList<UserRp>();
        contactUsers = new ArrayList<UserRp>();
        contactList = new ArrayList<EaseUser>();
        getContactList();
        //init list
        contactListLayout.init(contactList);
    }

    void setLinster() {
        mRightTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setNoticesPeople(getNoticesArray());
            }
        });
        contactListLayout.setOnUserEvent(this);
        listView.setOnItemClickListener(this);
        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }
        });
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                contactListLayout.filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
    }

    protected void getContactList() {
        contactList.clear();
        if (contactsMap == null) {
            return;
        }
        synchronized (this.contactsMap) {
            Iterator<Map.Entry<String, EaseUser>> iterator = contactsMap.entrySet().iterator();
            List<String> blackList = EMClient.getInstance().contactManager().getBlackListUsernames();
            while (iterator.hasNext()) {
                Map.Entry<String, EaseUser> entry = iterator.next();
                // to make it compatible with data in previous version, you can remove this check if this is new app
                if (!entry.getKey().equals("item_new_friends")
                        && !entry.getKey().equals("item_groups")
                        && !entry.getKey().equals("item_chatroom")
                        && !entry.getKey().equals("item_robots")) {
                    if (!blackList.contains(entry.getKey())) {
                        //filter out users in blacklist
                        EaseUser user = entry.getValue();
                        EaseCommonUtils.setUserInitialLetter(user);
                        contactList.add(user);
                    }
                }
            }
        }

        // sorting
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });

    }

    // refresh ui
    public void refresh() {
        RequestManager.postContacts(this, new ContactsCallback() {
            @Override
            public void onResult(List<UserRp> userRps) {
                Map<String, EaseUser> users = new Hashtable<String, EaseUser>();
                if (userRps == null) {
                    return;
                }
                contactUsers.clear();
                contactUsers.addAll(userRps);
                for (UserRp userRp : userRps) {
                    String username = userRp.userId;
                    String nickName = TextUtils.isEmpty(userRp.nickName) ? (TextUtils.isEmpty(userRp.uname) ? username : userRp.uname) : userRp.nickName;
                    String avatar = userRp.headImg;
                    EaseUser user = new EaseUser(username);
                    user.setNick(nickName);
                    user.setAvatar(avatar);
                    if (username.equals(EMConstant.NEW_FRIENDS_USERNAME) || username.equals(EMConstant.GROUP_USERNAME)
                            || username.equals(EMConstant.CHAT_ROOM) || username.equals(EMConstant.CHAT_ROBOT)) {
                        user.setInitialLetter("");
                    } else {
                        EaseCommonUtils.setUserInitialLetter(user);
                    }
                    users.put(username, user);
                }
                contactsMap = users;
                getContactList();
                contactListLayout.refresh();
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }


    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EaseUser user = (EaseUser) listView.getItemAtPosition(position);
        if (user != null) {
            boolean isBeprompt = isBePrompt(user.getUsername());
            if (isBeprompt) {
                removePrompt(user);
            } else {
                addPrompt(user);
            }
        }

    }

    @Override
    public void updatePromptContact() {
        updateNotices();
    }

    @Override
    public void initPromptContact() {
        updateNotices();
    }

    @Override
    public boolean isBePrompt(String userId) {
        if (notices == null)
            return false;
        for (UserRp userRp : notices) {
            if (TextUtils.equals(userRp.userId, userId)) {
                return true;
            }
        }
        return false;
    }

    //添加提示人
    void addPrompt(EaseUser user) {
        UserRp addUser = null;
        for (UserRp userRp : notices) {
            if (TextUtils.equals(userRp.userId, user.getUsername())) {
                contactListLayout.refresh();
                return;
            }
        }
        for (UserRp userRp : contactUsers) {
            if (TextUtils.equals(userRp.userId, user.getUsername())) {
                addUser = userRp;
            }
        }
        notices.add(addUser);
        contactListLayout.refresh();
    }

    //移除提示人
    void removePrompt(EaseUser user) {
        if (notices.size() != 0) {
            UserRp removeUser = null;
            for (UserRp userRp : notices) {
                if (TextUtils.equals(userRp.userId, user.getUsername())) {
                    removeUser = userRp;
                }
            }
            notices.remove(removeUser);
            contactListLayout.refresh();
        }
    }

    //获取提示人数组
    String[] getNoticesArray() {
        if (notices != null && notices.size() != 0) {
            String[] array = new String[notices.size()];
            for (int i = 0; i < notices.size(); i++) {
                array[i] = notices.get(i).userId;
            }
            return array;
        }
        return null;
    }

    //获取提示人
    void updateNotices() {
        RequestManager.postNotices(this, new ContactsCallback() {
            @Override
            public void onResult(List<UserRp> userRps) {
                if (userRps == null) {
                    return;
                }
                notices.clear();
                notices.addAll(userRps);
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }


    //设置提示人
    void setNoticesPeople(String[] userIds) {
        if (userIds == null || userIds.length == 0) {
            finish();
            return;
        }
        SetNoticesReq setNoticesReq = new SetNoticesReq();
        setNoticesReq.setUserIds(userIds);
        RequestManager.postSetNotices(mContext, setNoticesReq, new BaseRpCallback<BaseRopnse>() {

            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse baseRopnse) {
                ToastUtil.openBaseToast(mContext, R.string.string_prompt_ok, Toast.LENGTH_SHORT);
                finish();
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }

        });
    }

}
